﻿#include "hardwaretestdialog.h"
#include "ui_hardwaretestdialog.h"
#include "src/globalvar.h"
#include <QTime>

void HardwareTestDialog::OnPackage(ProtoData data)
{
    qDebug()<<"app receive hardware data"<<data.data<<" size "<<data.len;
    this->mWaitForResp = false;
    if(data.funcode == 0x01){
        ui->label_7->setText("执行成功");
    }
}

HardwareTestDialog::HardwareTestDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::HardwareTestDialog)
{
    ui->setupUi(this);
    this->setStyleSheet("QDialog#HardwareTestDialog QGroupBox#groupBox QLineEdit#lineEdit_3{background:black;}");
}

HardwareTestDialog::~HardwareTestDialog()
{
    delete ui;
}

void HardwareTestDialog::on_pushButton_clicked()
{
    if(!mWaitForResp){
        uint cnt = ui->lineEdit->text().toUInt();
        qDebug()<<cnt;
        MoveAxis(1,cnt);
    }
}

void HardwareTestDialog::on_pushButton_2_clicked()
{
    if(!mWaitForResp){
        uint16_t cnt = ui->lineEdit_2->text().toUInt();
        MoveAxis(2,cnt);
    }
}

void HardwareTestDialog::on_pushButton_3_clicked()
{
    if(!mWaitForResp){
        uint16_t cnt = ui->lineEdit_3->text().toUInt();
        MoveAxis(3,cnt);
    }
}

void HardwareTestDialog::on_pushButton_4_clicked()
{
    if(!mWaitForResp){
        uint16_t cnt = ui->lineEdit_4->text().toUInt();
        MoveAxis(4,cnt);
    }
}

void HardwareTestDialog::on_pushButton_5_clicked()
{
    if(!mWaitForResp){
        uint16_t cnt = ui->lineEdit_5->text().toUInt();
        MoveAxis(5,cnt);
    }
}

void HardwareTestDialog::on_pushButton_6_clicked()
{
    if(!mWaitForResp){
        uint16_t cnt = ui->lineEdit_6->text().toUInt();
        MoveAxis(6,cnt);
    }
}

int HardwareTestDialog::MoveAxis(uint8_t axis, uint16_t cnt)
{
    uint8_t data[3];
    memcpy(data + 1,&cnt,2);
    data[0] = axis;
    this->mWaitForResp = true;
    ui->label->setText(QStringLiteral("移动中"));
    int ret =GlobalVarManager::Instance()->SerialProto().WriteData(0x01,data,3);
    WaitForResponse();
    return ret;
}

int HardwareTestDialog::WaitForResponse()
{
    QTime    tmpTime;
    tmpTime.start();
    while (mWaitForResp) {
        QCoreApplication::processEvents();
        /*
        if(tmpTime.elapsed() > 3000){
            ui->label_7->setText("timeout");
            mWaitForResp = true;
        }*/
    }
    ui->label_7->setText("移动完成");
    return 0;
}
